package org.chen.controller;

import com.alibaba.nacos.common.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.chen.domain.dto.LoginDTO;
import org.chen.domain.dto.RegisterDTO;
import org.chen.domain.response.Result;
import org.chen.service.AuthService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import reactor.core.publisher.Mono;

@RestController
@RequestMapping("/auth")
@Validated
@Slf4j
public class AuthController {
    @Autowired
    private AuthService authService;

    /**
     * 验证token
     * @param token token
     * @return 真假
     */
    @PostMapping("/validate")
    public Mono<ResponseEntity<Boolean>> validateToken(@RequestHeader("Authorization") String token) {
        return Mono.fromSupplier(() -> {
            // 这里模拟 Token 验证逻辑，实际场景可以改为数据库查询、Redis 检查等
            boolean isValid = checkToken(token);
            return isValid ? ResponseEntity.ok(true) : ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(false);
        });
    }

    // 模拟 Token 验证逻辑
    private boolean checkToken(String token) {
        if (StringUtils.hasText(token) && token.startsWith("Bearer ")) {
            token = token.substring(7);
            // 这里可以调用 Redis、数据库或者解析 JWT 进行校验
            return authService.validateToken(token);
        }
        return false;
    }

    /**
     * 用户登录
     */
    @PostMapping("/login")
    public Result<String> login(@RequestBody @Validated LoginDTO loginDTO) {
        try {
            String token = authService.login(loginDTO);
            return Result.success("登录成功", token);
        } catch (BadCredentialsException e) {
            return Result.error("用户名或密码错误");
        } catch (Exception e) {
            log.error("登录失败", e);
            return Result.error("登录失败");
        }
    }

    /**
     * 用户注册
     */
    @PostMapping("/register")
    public Result<Void> register(@RequestBody @Validated RegisterDTO registerDTO) {
        try {
            authService.register(registerDTO);
//            return Result.success("注册成功");
            return Result.error("目前不允许注册");
        } catch (Exception e) {
            log.error("注册失败", e);
            return Result.error(e.getMessage());
        }
    }

    /**
     * 用户登出
     */
    @PostMapping("/logout")
    public Result<Void> logout() {
        try {
            authService.logout();
            return Result.success("登出成功");
        } catch (Exception e) {
            log.error("登出失败", e);
            return Result.error("登出失败");
        }
    }

    /**
     * 刷新token
     */
    @PostMapping("/refresh")
    public Result<String> refresh(@RequestHeader("Authorization") String token) {
        try {
            String newToken = authService.refreshToken(token);
            return Result.success("刷新成功", newToken);
        } catch (Exception e) {
            log.error("刷新token失败", e);
            return Result.error("刷新token失败");
        }
    }
}